package com.heima.controller;

import com.heima.annotation.OperationFill;
import com.heima.result.UploadResult;
import com.heima.util.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
@Api(tags = "通用接口")
@RequiredArgsConstructor
public class UploadController {

    private final AliOssUtil aliOssUtil;

    /**
     * 合同上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation("合同上传")
    @OperationFill
    public UploadResult upload(MultipartFile file){
        log.info("接收到的文件名称为:{}",file.getName());

        //原始文件名称
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));

        //将文件上传到阿里云
        String fileName = UUID.randomUUID().toString() + extension;
        try {
            String filePath = aliOssUtil.upload(file.getBytes(),fileName);
            return UploadResult.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败：{}",e.getMessage());
        }
        return UploadResult.error();
    }
}
